﻿/**************************************************************************
创建时间:	2020/2/29 17:27:24     
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com
	
Copyright (c) zhcun.cn

描	述：
记	录：
***************************************************************************/
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using ASmile.Extend;
using ASmile.ORM.Entitys;
using System.Reflection;

namespace ASmile.Win
{
    class JsonPropertyIgnore : DefaultContractResolver
    {
        public Func<Type, PropertyInfo, bool> IgnoreVerify;

        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var pList= base.CreateProperties(type, memberSerialization);
            if (IgnoreVerify == null)
            {
                return pList;
            }
            pList.ToList();
            for (int i = pList.Count - 1; i >= 0; i--)
            {
                var item = pList[i];
                PropertyInfo pInfo = type.GetProperty(item.PropertyName);
                if (IgnoreVerify(type, pInfo))
                {
                    pList.RemoveAt(i);
                }
            }

            return pList;
        }
    }

    /// <summary>
    /// json操作类
    /// </summary>
    public static class JsonHelper
    {
        static JsonHelper()
        {
            JsonSettring = new JsonSerializerSettings
            {
                DateFormatString = "yyyy-MM-dd HH:mm:ss",
                NullValueHandling = NullValueHandling.Ignore                
            };
        }

        readonly static JsonSerializerSettings JsonSettring;

        public static void SetPropertyIgnore(Func<Type, PropertyInfo, bool> IgnoreVerify)
        {
            JsonSettring.ContractResolver = new JsonPropertyIgnore 
            { 
                IgnoreVerify = IgnoreVerify
            };
        }

        /// <summary>
        /// 将指定对象序列化json字符串
        /// </summary>
        public static string ToJson(object obj)
        {
            //if (obj == null) return null; //试试会不会报错
            return JsonConvert.SerializeObject(obj, Formatting.Indented, JsonSettring);
        }
        /// <summary>
        /// 将json字符串转成对象
        /// </summary>
        public static object JsonToObject(string data)
        {
            return JsonConvert.DeserializeObject(data, JsonSettring);
        }
        /// <summary>
        /// 通过json字符串序列化成对象
        /// </summary>
        public static T JsonToObject<T>(string data)
        {
            return JsonConvert.DeserializeObject<T>(data, JsonSettring);
        }
    }
}